<template>
  <div class="document-container">
    <el-card class="document-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><FolderOpened /></el-icon>
            项目资料管理
            <el-tag v-if="props.projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ props.projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            项目资料管理，文档版本控制
            <span v-if="props.projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ props.projectData.project_id }})
            </span>
          </p>
        </div>
        <div class="header-actions">
          <el-button v-if="canAdd" type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            添加资料
          </el-button>
          <el-button type="primary" @click="refreshData" class="refresh-btn" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>

      <!-- 项目选择 -->
      <div class="project-selector" v-if="!props.projectData.project_id">
        <el-select v-model="selectedProject" placeholder="选择项目" style="width: 300px" @change="handleProjectChange">
          <el-option label="全部项目" value="all" />
          <el-option 
            v-for="project in projectList" 
            :key="project.project_id" 
            :label="project.project_name" 
            :value="project.project_id" 
          />
        </el-select>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索资料类型、主要内容..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterDocType" placeholder="资料类型" clearable>
          <el-option 
            v-for="docType in docTypeOptions" 
            :key="docType" 
            :label="docType" 
            :value="docType" 
          />
        </el-select>
        <el-select v-model="filterAuditStatus" placeholder="审核状态" clearable>
          <el-option label="待审核" value="pending" />
          <el-option label="已审核" value="approved" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="已发送" value="sent" />
        </el-select>
      </div>

      <!-- 资料列表 -->
      <el-table
        :data="paginatedDocumentList"
        stripe
        border
        class="document-table"
        v-loading="loading"
        empty-text="暂无资料"
      >
        <el-table-column prop="doc_type" label="资料类型" min-width="150" />
        <el-table-column prop="project_id" label="所属项目" width="120" />
        <el-table-column prop="doc_code" label="资料编号" width="120" />
        <el-table-column prop="content" label="主要内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="pages" label="页数" width="80" />
        <el-table-column prop="copies" label="份数" width="80" />
        <el-table-column prop="author" label="编制人" width="100" />
        <el-table-column prop="audit_status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getAuditStatusTagType(scope.row.audit_status)" size="small">
              {{ getAuditStatusText(scope.row.audit_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="send_date" label="发出时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.send_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="receiver" label="接收人" width="100" />
        <el-table-column prop="signed_date" label="签字时间" width="120">
          <template #default="scope">
            {{ scope.row.signed_date ? formatDate(scope.row.signed_date) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="problem" label="存在问题" min-width="150" show-overflow-tooltip />
        <el-table-column label="附件文件" width="150">
          <template #default="scope">
            <div v-if="scope.row.filename && scope.row.fileurl" class="file-actions">
              <div class="file-info">
                <div class="file-header">
                  <el-icon class="file-icon" :class="getFileIconClass(scope.row.filename)">
                    <Document v-if="isDocumentFile(scope.row.filename)" />
                    <Picture v-else-if="isImageFile(scope.row.filename)" />
                    <Files v-else />
                  </el-icon>
                  <span class="filename">{{ scope.row.filename }}</span>
                </div>
                <el-button 
                  size="small" 
                  type="success" 
                  @click="downloadFile(scope.row.fileurl, scope.row.filename)"
                  class="download-btn"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
              </div>
            </div>
            <span v-else class="no-file">无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" v-if="hasPermission">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button size="small" type="warning" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button v-if="canAdd" size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section" v-if="filteredDocumentList.length > 0">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredDocumentList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 资料统计 -->
      <div class="document-stats">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ documentStats.total }}</div>
                <div class="stat-label">总资料数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ documentStats.totalPages }}</div>
                <div class="stat-label">总页数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ documentStats.totalCopies }}</div>
                <div class="stat-label">总份数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ documentStats.docTypes }}</div>
                <div class="stat-label">资料类型数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ documentStats.totalFiles }}</div>
                <div class="stat-label">附件文件数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 资料创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑资料' : '添加资料'"
      width="800px"
      align-center
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目" prop="project_id">
              <el-select v-model="form.project_id" placeholder="请选择项目" style="width: 100%" :disabled="!!props.projectData.project_id">
                <el-option 
                  v-for="project in projectList" 
                  :key="project.project_id" 
                  :label="project.project_name" 
                  :value="project.project_id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料类型" prop="doc_type">
              <el-select 
                v-model="form.doc_type" 
                placeholder="请选择或输入资料类型" 
                style="width: 100%"
                filterable
                allow-create
                default-first-option
              >
                <el-option 
                  v-for="docType in predefinedDocTypes" 
                  :key="docType" 
                  :label="docType" 
                  :value="docType"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资料编号" prop="doc_code">
              <el-input v-model="form.doc_code" placeholder="请输入资料编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编制人" prop="author">
              <el-input v-model="form.author" placeholder="请输入编制人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="主要内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="3" placeholder="请输入主要内容" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="页数" prop="pages">
              <el-input-number v-model="form.pages" :min="1" style="width: 100%" placeholder="请输入页数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="份数" prop="copies">
              <el-input-number v-model="form.copies" :min="1" style="width: 100%" placeholder="请输入份数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核状态" prop="audit_status">
              <el-select v-model="form.audit_status" placeholder="请选择审核状态" style="width: 100%">
                <el-option label="待审核" value="pending" />
                <el-option label="已审核" value="approved" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已发送" value="sent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发出时间" prop="send_date">
              <el-date-picker
                v-model="form.send_date"
                type="date"
                placeholder="选择发出时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收人" prop="receiver">
              <el-input v-model="form.receiver" placeholder="请输入接收人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签字时间" prop="signed_date">
              <el-date-picker
                v-model="form.signed_date"
                type="date"
                placeholder="选择签字时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="存在问题" prop="problem">
          <el-input v-model="form.problem" type="textarea" :rows="3" placeholder="请输入存在的问题" />
        </el-form-item>
        <el-form-item label="附件文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeFileUpload"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar"
            class="file-upload"
          >
            <template #trigger>
              <el-button type="primary" size="small">
                <el-icon><Plus /></el-icon>
                选择文件
              </el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、Excel、文本、压缩包等格式，文件大小不超过50MB
              </div>
            </template>
          </el-upload>
          
          <!-- 显示已有文件信息 -->
          <div v-if="form.filename && form.fileurl" class="existing-file">
            <el-alert
              title="当前附件文件"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <div class="file-info-display">
                  <span class="filename">{{ form.filename }}</span>
                  <el-button 
                    size="small" 
                    type="success" 
                    @click="downloadFile(form.fileurl, form.filename)"
                    class="download-btn"
                  >
                    <el-icon><Download /></el-icon>
                    下载
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="removeExistingFile"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                    移除
                  </el-button>
                </div>
              </template>
            </el-alert>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 资料详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="资料详情"
      width="800px"
      align-center
    >
      <div class="document-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="资料类型">{{ selectedDocument.doc_type }}</el-descriptions-item>
          <el-descriptions-item label="所属项目">{{ selectedDocument.project_id }}</el-descriptions-item>
          <el-descriptions-item label="资料编号">{{ selectedDocument.doc_code || '-' }}</el-descriptions-item>
          <el-descriptions-item label="编制人">{{ selectedDocument.author }}</el-descriptions-item>
          <el-descriptions-item label="页数">{{ selectedDocument.pages }}</el-descriptions-item>
          <el-descriptions-item label="份数">{{ selectedDocument.copies }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getAuditStatusTagType(selectedDocument.audit_status)" size="small">
              {{ getAuditStatusText(selectedDocument.audit_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发出时间">{{ formatDate(selectedDocument.send_date) }}</el-descriptions-item>
          <el-descriptions-item label="接收人">{{ selectedDocument.receiver }}</el-descriptions-item>
          <el-descriptions-item label="签字时间">{{ selectedDocument.signed_date ? formatDate(selectedDocument.signed_date) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="主要内容" :span="2">
            {{ selectedDocument.content || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="存在问题" :span="2">
            {{ selectedDocument.problem || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedDocument.remark || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="附件文件" :span="2" v-if="selectedDocument.filename && selectedDocument.fileurl">
            <div class="file-info-display">
              <div class="file-detail-info">
                <span class="filename">{{ selectedDocument.filename }}</span>
                <span class="file-url">{{ selectedDocument.fileurl }}</span>
              </div>
              <el-button 
                size="small" 
                type="success" 
                @click="downloadFile(selectedDocument.fileurl, selectedDocument.filename)"
                class="download-btn"
              >
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FolderOpened, Plus, Search, View, Edit, Delete, Refresh, Download, Document, Picture, Files } from '@element-plus/icons-vue'
import { 
  getProjectDocumentsList, 
  getProjectDocumentsListByProjectId,
  createProjectDocuments, 
  updateProjectDocuments, 
  deleteProjectDocuments 
} from '../../api/projectDocuments'
import { getProjectList } from '../../api/project'
import { uploadSingleFile } from '../../api/fileUpload'
import apiConfig from '../../utils/apiConfig'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否可以新增和删除（只有当前项目的项目经理可以操作）
const canAdd = computed(() => {
  return isProjectManager.value
})

// 预定义的资料类型
const predefinedDocTypes = [
  '技术文档',
  '设计文档',
  '需求文档',
  '测试文档',
  '用户手册',
  '操作手册',
  '维护手册',
  '项目计划',
  '项目报告',
  '会议纪要',
  '合同文档',
  '验收文档',
  '培训材料',
  '规范标准',
  '图纸文件',
  '源代码',
  '数据库文档',
  '接口文档'
]

// 响应式数据
const selectedProject = ref('all')
const documentList = ref([])
const projectList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const searchKeyword = ref('')
const filterDocType = ref('')
const filterAuditStatus = ref('')
const formRef = ref()
const selectedDocument = ref({})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const form = ref({
  id: null,
  project_id: '',
  doc_type: '',
  doc_code: '',
  content: '',
  pages: 1,
  copies: 1,
  author: '',
  audit_status: 'pending',
  send_date: '',
  receiver: '',
  signed_date: '',
  problem: '',
  remark: '',
  file: null, // 新增文件上传字段
  filename: '',
  fileurl: ''
})

// 表单验证规则
const formRules = {
  project_id: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  doc_type: [{ required: true, message: '请输入资料类型', trigger: 'blur' }],
  content: [{ required: true, message: '请输入主要内容', trigger: 'blur' }],
  pages: [{ required: true, message: '请输入页数', trigger: 'blur' }],
  copies: [{ required: true, message: '请输入份数', trigger: 'blur' }],
  author: [{ required: true, message: '请输入编制人', trigger: 'blur' }],
  audit_status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  send_date: [{ required: true, message: '请选择发出时间', trigger: 'change' }],
  receiver: [{ required: true, message: '请输入接收人', trigger: 'blur' }]
  // 文件上传是可选的，不需要验证
}

// 资料类型选项
const docTypeOptions = computed(() => {
  const options = new Set()
  documentList.value.forEach(doc => {
    if (doc.doc_type) {
      options.add(doc.doc_type)
    }
  })
  return Array.from(options)
})

// 过滤后的资料列表
const filteredDocumentList = computed(() => {
  let filtered = documentList.value
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.doc_type?.toLowerCase().includes(keyword) ||
      item.content?.toLowerCase().includes(keyword) ||
      item.doc_code?.toLowerCase().includes(keyword) ||
      item.author?.toLowerCase().includes(keyword) ||
      item.receiver?.toLowerCase().includes(keyword) ||
      item.filename?.toLowerCase().includes(keyword) // 添加文件名搜索
    )
  }
  
  // 根据资料类型过滤
  if (filterDocType.value) {
    filtered = filtered.filter(item => item.doc_type === filterDocType.value)
  }
  
  // 根据审核状态过滤
  if (filterAuditStatus.value) {
    filtered = filtered.filter(item => item.audit_status === filterAuditStatus.value)
  }
  
  return filtered
})

// 分页后的资料列表
const paginatedDocumentList = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredDocumentList.value.slice(start, end)
})

// 资料统计数据
const documentStats = computed(() => {
  const total = filteredDocumentList.value.length
  const totalPages = filteredDocumentList.value.reduce((sum, item) => sum + (item.pages || 0), 0)
  const totalCopies = filteredDocumentList.value.reduce((sum, item) => sum + (item.copies || 0), 0)
  const docTypes = new Set(filteredDocumentList.value.map(item => item.doc_type)).size
  const totalFiles = filteredDocumentList.value.filter(item => item.filename && item.fileurl).length
  
  return { total, totalPages, totalCopies, docTypes, totalFiles }
})

// 获取审核状态标签样式
function getAuditStatusTagType(status) {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'sent': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取审核状态文本
function getAuditStatusText(status) {
  const statusMap = {
    'pending': '待审核',
    'approved': '已审核',
    'rejected': '已拒绝',
    'sent': '已发送'
  }
  return statusMap[status] || status
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取项目列表
async function loadProjectList() {
  try {
    const response = await getProjectList({ page: 1, pageSize: 1000 })
    if (response.data && response.data.data) {
      projectList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      projectList.value = response.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 加载项目资料列表
async function loadProjectDocuments() {
  loading.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId || selectedProject.value
    
    if (currentProjectId && currentProjectId !== 'all') {
      console.log('加载项目资料，项目ID:', currentProjectId)
      
      const res = await getProjectDocumentsListByProjectId(currentProjectId)
      const allDocuments = Array.isArray(res) ? res : []
      
      // 过滤当前项目的数据
      documentList.value = allDocuments.filter(item => item.project_id === currentProjectId)
      console.log('当前项目资料数量:', documentList.value.length)
      console.log('资料数据:', documentList.value)
    } else {
      // 加载所有资料
      const response = await getProjectDocumentsList({ page: 1, pageSize: 1000 })
      if (response.data && response.data.data) {
        documentList.value = response.data.data
      } else if (Array.isArray(response.data)) {
        documentList.value = response.data
      } else {
        documentList.value = []
      }
    }
  } catch (error) {
    ElMessage.error('加载项目资料失败')
    console.error('加载项目资料失败:', error)
    documentList.value = []
  } finally {
    loading.value = false
  }
}

// 项目选择变化
function handleProjectChange() {
  loadProjectDocuments()
}

// 刷新数据
function refreshData() {
  loadProjectDocuments()
}

// 打开对话框
function openDialog(document = null) {
  if (document) {
    form.value = { ...document }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || (selectedProject.value === 'all' ? '' : selectedProject.value),
      doc_type: predefinedDocTypes[0] || '',
      doc_code: '',
      content: '',
      pages: 1,
      copies: 1,
      author: '',
      audit_status: 'pending',
      send_date: '',
      receiver: '',
      signed_date: '',
      problem: '',
      remark: '',
      file: null,
      filename: '',
      fileurl: ''
    }
  }
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 如果有文件，先上传文件
    let fileInfo = {}
    if (form.value.file) {
      try {
        console.log('开始上传文件:', form.value.file)
        console.log('文件类型:', typeof form.value.file)
        console.log('文件大小:', form.value.file.size)
        console.log('文件名称:', form.value.file.name)
        
        const uploadResponse = await uploadSingleFile(form.value.file)
        console.log('上传响应:', uploadResponse)
        
        if (uploadResponse.data && uploadResponse.data.url) {
          fileInfo = {
            filename: form.value.file.name,
            fileurl: uploadResponse.data.url
          }
          ElMessage.success('文件上传成功')
        } else {
          throw new Error('文件上传失败')
        }
      } catch (error) {
        console.error('文件上传失败:', error)
        console.error('错误详情:', {
          name: error.name,
          message: error.message,
          stack: error.stack,
          response: error.response
        })
        ElMessage.error(`文件上传失败: ${error.message}`)
        return
      }
    }
    
    // 准备提交的数据
    const submitData = { ...form.value }
    if (Object.keys(fileInfo).length > 0) {
      submitData.filename = fileInfo.filename
      submitData.fileurl = fileInfo.fileurl
    }
    
    if (form.value.id) {
      // 更新
      await updateProjectDocuments(form.value.id, submitData)
      ElMessage.success('资料更新成功')
    } else {
      // 创建
      await createProjectDocuments(submitData)
      ElMessage.success('资料创建成功')
    }
    
    dialogVisible.value = false
    loadProjectDocuments()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
function viewDetail(document) {
  selectedDocument.value = document
  detailVisible.value = true
}

// 删除资料
async function handleDelete(id) {
  try {
    await ElMessageBox.confirm('确定要删除这个资料吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProjectDocuments(id)
    ElMessage.success('删除成功')
    loadProjectDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 分页处理
function handleSizeChange(newSize) {
  pagination.value.pageSize = newSize
  pagination.value.page = 1
}

function handleCurrentChange(newPage) {
  pagination.value.page = newPage
}

// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    loadProjectDocuments()
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载项目资料:', newProjectId)
    loadProjectDocuments()
  }
})

// 文件上传相关
const uploadRef = ref()

// 文件类型判断函数
function isDocumentFile(filename) {
  const docExtensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt', '.csv']
  const ext = filename.toLowerCase().substring(filename.lastIndexOf('.'))
  return docExtensions.includes(ext)
}

function isImageFile(filename) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
  const ext = filename.toLowerCase().substring(filename.lastIndexOf('.'))
  return imageExtensions.includes(ext)
}

function getFileIconClass(filename) {
  if (isDocumentFile(filename)) return 'document-icon'
  if (isImageFile(filename)) return 'image-icon'
  return 'file-icon'
}

async function beforeFileUpload(rawFile) {
  const isLt50M = rawFile.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  return true
}

async function handleFileChange(file) {
  console.log('文件变更事件:', file)
  console.log('原始文件对象:', file.raw)
  
  // 确保文件对象正确
  if (file.raw && file.raw instanceof File) {
    form.value.file = file.raw
    console.log('文件已设置到表单:', form.value.file)
  } else {
    console.error('无效的文件对象:', file.raw)
    ElMessage.error('文件选择失败，请重试')
  }
}

async function handleFileRemove() {
  form.value.file = null
}

// 移除已有文件
function removeExistingFile() {
  form.value.file = null
  form.value.filename = ''
  form.value.fileurl = ''
  ElMessage.success('已移除附件文件')
}

// 下载文件
async function downloadFile(fileUrl, fileName) {
  try {
    console.log('开始下载文件:', fileName, 'URL:', fileUrl)
    
    // 从fileUrl中提取文件类型和文件名
    // fileUrl格式: /uploads/application/filename.ext
    const urlParts = fileUrl.split('/')
    const fileType = urlParts[urlParts.length - 2] // 获取文件类型目录
    const filename = urlParts[urlParts.length - 1] // 获取文件名
    
    console.log('解析的文件信息:', { fileType, filename })
    
    // 使用新的下载API
    const baseURL = apiConfig.getBaseURLSync()
    const downloadUrl = `${baseURL}/api/upload/download/${filename}?type=${fileType}`
    
    console.log('下载URL:', downloadUrl)
    
    // 创建一个隐藏的a标签来下载文件
    const link = document.createElement('a')
    link.href = downloadUrl
    link.setAttribute('download', fileName)
    link.setAttribute('target', '_blank')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('文件下载已开始')
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('文件下载失败')
  }
}

// 页面初始化
onMounted(async () => {
  try {
    await loadProjectList()
    await loadProjectDocuments()
  } catch (error) {
    console.error('项目资料管理页面初始化失败:', error)
  }
})
</script>

<style scoped>
.document-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.document-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #67c23a;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn, .refresh-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.project-selector {
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.document-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.document-stats {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.document-detail {
  padding: 20px 0;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}

.file-upload {
  margin-bottom: 10px;
}

.existing-file {
  margin-top: 10px;
}

.file-info-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-detail-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filename {
  font-weight: 500;
  color: #606266;
}

.file-url {
  font-size: 12px;
  color: #909399;
  word-break: break-all;
}

.download-btn, .remove-btn {
  margin-left: 10px;
}

.file-actions {
  display: flex;
  justify-content: center;
}

.file-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.file-header {
  display: flex;
  align-items: center;
  gap: 5px;
}

.file-icon {
  font-size: 16px;
}

.document-icon {
  color: #409eff;
}

.image-icon {
  color: #67c23a;
}

.file-icon {
  color: #909399;
}

.file-info .filename {
  font-size: 12px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-file {
  color: #909399;
  font-size: 12px;
}
</style> 